package com.afdor.rws.event.driven.support.holder;

import com.afdor.rws.core.Callback;
import com.afdor.rws.event.driven.api.EventHolder;
import com.afdor.rws.event.driven.commons.ThreadUtils;
import com.afdor.rws.event.driven.entities.Event;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;

import java.io.Serializable;

/**
 * 回调事件对象
 *
 * @author 悭梵
 * @date Created in 2018-12-10 15:24
 */
@AllArgsConstructor
public final class CallbackEvent<V> implements Serializable, EventHolder {

    @Getter
    @NonNull
    private final Event event;
    @Getter
    private final Callback callback;

    /**
     * 事件处理成功
     *
     * @param data
     */
    public void complete(EventResult<V> data) {
        this.event.setStatus(Event.Status.RESULTED);
        if (this.callback != null) {
            this.callback.call(data);
        }
    }

    /**
     * 处理异常
     *
     * @param e
     */
    public void failureExceptionally(Throwable e) {
        this.event.setStatus(Event.Status.RESULT_FAILURED);
        EventResult<V> result = new EventResult<>(this.event);
        result.setCode(0);
        result.setMessage(ThreadUtils.getStackMessage(e));
        if (this.callback != null) {
            this.callback.call(result);
        }
    }
}
